/**
 * 发送http请求
 * 依赖 md5.js 用于建立缓存
 * 依赖 zbNotice.js 用于提醒
 */
let zbCache = {}
const zbRequest = function () {
    this.cacheTime = 300;
    this.successCode = 1;
    this.success = null;
    this.error = null;
    this.sync = false; //true:异步 false:同步
    this.method = 'post'; //post/get
    this.defaultParams = {}; //默认参数
    this.tmpParams = {}; //临时参数, 每次请求后会清空
    this.rawResponse = {};
    this.responseData = {};
    this.responseMsg = '';
    this.isRedirect = false;

    //默认成功回调
    this.defaultSuccess = function () {
        alert('操作成功！');
    }

    //默认错误回调
    this.defaultError = function (msg=null) {
        if (msg && this.isRedirect === false) {
            alert(msg);
        } else {
            alert('操作失败！');
        }
    }

    this.handleResponse = function (response) {
        this.rawResponse = response;
        let rs = JSON.parse(response);
        if (rs) {
            this.responseData = rs['data'];
            this.responseMsg = rs['msg'];
            if (rs['code'] === this.successCode) {
                return true;
            } else {
                //接口返回失败, 如果data中url有值, 就跳转
                if (this.responseData.url) {
                    this.isRedirect = true;
                    location.href = this.responseData.url;
                    return false;
                } else {
                    return false;
                }
            }
        } else {
            this.responseMsg = '未能解析返回数据';
            return false;
        }
    }

    //获取时间戳
    this.getTimestamp = function(){
        let now = (new Date()).getTime();
        now = now.toString().slice(0, -3);
        return parseInt(now);
    }

    //获取信息摘要
    this.getHash = function (src, arg) {
        return hex_md5(src + JSON.stringify(arg)); //依赖md5.js
    }

    //获取缓存
    this.getCache = function(src, arg) {
        let key = this.getHash(src, arg);

        if (zbCache[key] === undefined) {
            console.log('未找到缓存: ' + src + ' ' +key);
            return null;
        } else {
            let expire = parseInt(zbCache[key]['expire']);
            let now = this.getTimestamp();
            if (now >= expire) {
                console.log('缓存已过期 ' + src);
                return null;
            } else {
                console.log('找到缓存 ' + src);
                return zbCache[key]['data'];
            }
        }
    }

    this.setCache = function(src, arg, data, expire) {
        let key = this.getHash(src, arg);
        let now = this.getTimestamp();

        expire = now + expire;
        zbCache[key] = {expire:expire, data:data}
    }

    //请求接口
    this.request = function (src, params = {}, success = null, expire=300) {
        for (let k in this.defaultParams) {
            if (params[k] === 'undefined') {
                params[k] = this.defaultParams[k];
            }
        }

        if (this.tmpParams) {
            for (let k in this.tmpParams) {
                params[k] = this.tmpParams[k];
            }
            this.tmpParams = {};
        }

        let cache = (expire !== 0) ? this.getCache(src, params) : null;
        if (cache !== null && typeof success === 'function') {
            success(cache);
            return;
        }

        let that = this;

        let form = new FormData(); // FormData 对象
        let xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
        xhr.open(that.method, src, that.async); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
        xhr.onload = function (evt) {
            if (that.handleResponse(xhr.response)) {
                that.setCache(src, params, that.responseData, expire);
                if (typeof success === 'function') {
                    success(that.responseData);
                }
            } else {
                that.defaultError(that.responseMsg)
                return false;
            }
        }

        //请求失败
        xhr.onerror =  function(evt) {
            console.log(xhr.response);
            that.defaultError();
        };

        //请求超时
        xhr.ontimeout =  function(evt) {
            that.defaultError('请求超时.');
        };

        for (let i in params) {
            form.append(i, params[i]);
        }

        xhr.send(form); //开始上传，发送form数据
    }

    this.fetchPost = function (url, param, callback) {
        fetch(url,{
            method:'POST', mode:'cors', cache:'no-cache', credentials:'same-origin', redirect:'follow', referrerPolicy:'no-referrer',
            headers:{
                'Content-Type': 'application/json',
                //'user-agent': "Mozilla/4.0 MDN Example",
                //'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: JSON.stringify(param)
        })
            .then(function(res){console.log(res); return res.json();})
            .then(function (response) {
                if (typeof callback === 'function') {
                    console.log(response)
                    callback(response);
                }
            })
    }
}
